package com.example.meeting.shiro;

import com.example.meeting.model.domain.Admin;
import com.example.meeting.service.IAdminService;
import com.example.meeting.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {
    
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private IAdminService adminService;

    /**
     * 自定义所支持校验的token类型,需和subject.login()中的参数类型保持一致
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        // 判断token是否为JwtToken类型
        return token instanceof JwtToken;
    }

    /**
     * 身份认证
     * 每调用一次subject.login()或进行权限认证时会调用该方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("身份认证");
        JwtToken jwtToken = (JwtToken) token;
        
        Claims claims = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal());
        //用户名
        String username = claims.get("username",String.class);
        //根据用户名查询数据库对应的管理员信息
        Admin admin = adminService.authenticationByUsername(username);
        if(admin == null){
            throw new UnknownAccountException("不存在该用户信息");
        }else{
            return new SimpleAuthenticationInfo(admin,jwtToken.getCredentials(),getName());
        }
    }

    /**
     * 权限认证
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}